import Vue from 'vue'
import VueRouter from 'vue-router'
import login from '../components/Login'
import home from '../components/Home'
import Welcome from '@/components/Welcome'
import Users from '@/components/user/Users'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    component: login
  },
  {
    path: '/home',
    component: home,
    redirect: '/welcome',
    children: [
      {
        path: '/welcome',
        component: Welcome
      },
      {
        path: '/users',
        component: Users
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 为router实例对象设置导航守卫
router.beforeEach((to, from, next) => {
  // 如果用户要访问Login，直接放行
  if (to.path === '/login') return next()
  // 如果用户要访问其他的页面，先检测token是否存在
  const tokenStr = window.sessionStorage.getItem('token')
  // 如果token不存在，说明用户未登录，强制跳转至Login
  if (!tokenStr) return next('/login')
  next()
})

export default router
